<template>
  <el-card shadow="never" class="index">
    <!-- 系统用户查询 -->
    <el-form
      ref="searchRef"
      :model="data.search"
      label-width="80px"
      :inline="true"
      size="small"
    >
      <el-row :gutter="24">
        <el-col v-for="(item, i) in demoSearch" v-bind="colLayout" :key="i">
          <!-- 默认项 -->
          <el-form-item
            v-if="item.type == 'select'"
            :label="item.label"
            :prop="item.prop"
          >
            <el-select
              v-model="data.search[item.prop]"
              class="width_100"
              :placeholder="`请选择${item.label}`"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- input -->
          <el-form-item
            v-if="item.type == 'input'"
            :label="item.label"
            :prop="item.prop"
          >
            <el-input
              class="width_100"
              v-model="data.search[item.prop]"
              :placeholder="`请输入${item.label}`"
            />
          </el-form-item>
        </el-col>
        <!-- 按钮 -->
        <el-col v-bind="colBtn">
          <div class="flex_just_end" style="padding-bottom: 12px">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit({}, 'add')"
            >
              新增
            </el-button>
            <el-button size="small" type="danger" @click="handleMoreDetele()">
              批量删除
            </el-button>
            <el-button size="small" type="primary" @click="handleSearch">
              查询
            </el-button>
            <el-button size="small" @click="resetForm(searchRef)">
              重置
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 用户列表 -->
    <el-table
      border
      height="540"
      style="width: 100%"
      :data="data.dataSource"
      v-loading="data.loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        align="center"
        width="40"
      />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          <span
            class="ellipsis"
            v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
          ></span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, i) in data.cloums"
        :key="i"
        :width="item.width"
        :prop="item.prop"
        :label="item.label"
        :align="
          item.type == 'money' || item.type == 'number' ? 'right' : 'center'
        "
      >
        <template #header>
          <span class="text_center">{{ item.label }}</span>
        </template>
        <template #default="{ row }">
          <!-- 自定义 -->
          <div v-if="item.type == 'custom'">
            <span v-if="item.prop == 'avatar'">
              <img
                class="previewImg"
                v-if="row.avatar"
                :src="row.avatar"
                alt=""
                @click="previewImgRef.open(row.avatar)"
              />
              <span v-else>--</span>
            </span>
            <span v-if="item.prop == 'status'">
              <el-tag :type="statusColor(row.status, true)">
                {{ statusColor(row.status, false) }}
              </el-tag>
            </span>
            <span v-if="item.prop == 'sex'">
              {{ row.sex ? "男" : "女" }}
            </span>
            <span
              v-if="item.prop == 'phone'"
              @click="row.isEphone = !row.isEphone"
            >
              <span class="el-icon-view"></span>
              {{ row.isEphone ? "****" : row.phone }}
            </span>
          </div>
          <!-- 默认 -->
          <div v-else class="ellipsis">
            {{ FieldFormat(row[item.prop], item.type) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row, 'edit')">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDetele(row)">
            删除
          </el-button>

          <router-link :to="`/system/systemUserDetail?id=${row.id}`">
            <el-button link type="info">查看详情</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->

    <footer class="footer">
      <el-pagination
        background
        small="small"
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        layout="total, prev, pager, next,sizes, jumper"
        :page-sizes="[20, 50, 100, 200]"
        :pager-count="10"
        :total="data.count"
        @current-change="handlePageNum"
        @size-change="handlePageSize"
      />
    </footer>

    <!-- 图片预览 -->
    <PreviewImg ref="previewImgRef" />
    <!-- 新建及更新 -->
    <UpdateDialog ref="updateDialogRef" @refreshPage="getUserInfoList()" />
  </el-card>
</template>

<script setup>
  /**
   * 引入
   */
  import { reactive, onMounted, ref } from "vue";
  import { testsapi } from "/@/api/index";

  import { demoSearch, demoCloums } from "./components/tools";
  import PreviewImg from "/@/components/PreviewImg.vue";
  import UpdateDialog from "./components/UpdateDialog.vue";
  import { FieldFormat, ArrayOneValue } from "/@/utils/utils";

  /**
   * 定义：var
   */
  const colLayout = {
    xs: 24,
    sm: 12,
    md: 12,
    lg: 8,
    xl: 6,
  };
  const colBtn = {
    xs: 24,
    sm: 24,
    md: 24,
    lg: 24,
    xl: 24,
  };

  const previewImgRef = ref();
  const updateDialogRef = ref();
  const searchRef = ref();

  const currentRow = ref([]);

  const data = reactive({
    dataSource: [],
    cloums: [],
    pageNum: 1,
    pageSize: 20,
    count: 0,
    search: {},
    summary: null,
  });
  data.dataSource = [];
  data.cloums = demoCloums;

  /**
   * 方法：method
   */
  // 多选
  const handleSelectionChange = (value) => {
    currentRow.value = value;
  };

  const handlePageNum = (value) => {
    data.pageNum = value;
    getUserInfoList();
  };
  // 页数筛选
  const handlePageSize = (value) => {
    data.pageSize = value;
    getUserInfoList();
  };

  const handleSearch = async (value = "") => {
    await getUserInfoList();
    ElMessage({
      message: "查询成功",
      center: true,
    });
  };

  // 重置
  const resetForm = async (formEl) => {
    if (!formEl) return;
    await formEl.resetFields();
    await getUserInfoList();
    ElMessage({
      message: "重置成功",
      center: true,
    });
  };

  // 删除
  /**
   *
   * @param {*} id 通过id 删除
   */
  const handleDetele = ({ id }) => {
    ElMessageBox.confirm("确认删除此条数据?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 请求接口
        // api({id})

        ElMessage({
          type: "success",
          message: "删除成功!",
        });
      })
      .catch(() => {
        ElMessage({
          type: "warning",
          message: "删除失败!",
        });
      });
  };
  // 批量删除
  const handleMoreDetele = () => {
    if (!currentRow.value.length) {
      ElMessage({
        type: "da",
        message: "操作数据不能为空!",
      });
      return;
    }

    ElMessageBox.confirm("确认删除多条数据? 请谨慎操作!", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 数组 某一字段 集合
        const _id = ArrayOneValue(currentRow.value, "id");

        console.log(_id, "idjihe"); //['1714471285016895490', '1737378040662511617', '1737378355893817346']

        // ArrayOneValue

        // 请求接口
        // api({id : _id})

        ElMessage({
          type: "success",
          message: "删除成功!",
        });
      })
      .catch(() => {
        ElMessage({
          type: "warning",
          message: "删除失败!",
        });
      });
  };
  // 查看详情
  const handleDetail = ({ id }) => {};

  // 编辑
  /**
   *
   * @param {*} row 每条数据
   * @param {*} type 新增或者编辑
   */
  const handleEdit = (row, type) => {
    updateDialogRef.value.open(row, type);
  };

  // 状态tag_color
  const statusColor = (value, flag = false) => {
    let obj = { type: "info", text: "--" };

    switch (value) {
      case 1:
        obj = {
          type: "success",
          text: "已完成",
        };
        break;
      case 2:
        obj = {
          type: "success",
          text: "已确认",
        };
        break;
      default:
        obj = {
          type: "danger",
          text: "已取消",
        };
        break;
    }
    return flag ? obj.type : obj.text;
  };

  // 用户-分页列表查询
  const getUserInfoList = async () => {
    const search = data.search;

    try {
      let query = {
        avatar: search.avatar || "", //头像
        birthday: search.birthday || "", //生日
        delFlag: search.delFlag || "", //删除状态
        departIds: search.departIds || "", //负责部门
        email: search.email || "", //电子邮件
        pageNo: data.pageNum || 1,
        pageSize: data.pageSize || 10,
        phone: search.phone || "", //电话
        post: search.post || "", //职务
        postText: search.postText || "", //职位名称
        realname: search.realname || "", //真实姓名
        sex: search.sex || "", //性别
        status: search.status || "", //状态
        telephone: search.telephone || "", //座机号
        username: search.username || "", //登录账号
        workNo: search.workNo || "", //	工号
      };

      let res = await testsapi.GetListAll({ ...query });
      const { code, result } = res.data;

      if (code != 200) return;
      data.dataSource = result?.records.map((item) => {
        return {
          ...item,
          isEphone: true, // 加密 isE + 加密字段
        };
      });
      data.count = result?.total || 0;
    } catch (error) {}
  };

  onMounted(() => {
    getUserInfoList();
  });
</script>

<style lang="scss" scoped>
  .card_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .userList :empty::before {
    contain: "-";
  }

  @import "./components/index.scss";
</style>
